import { createRouter, createWebHistory } from 'vue-router'
import pinia from '@/pinia'
import useLoginStore from '@/stores/login'

const loginStore = useLoginStore(pinia)

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: () => import('@/views/Layout/index.vue'),
      redirect: '/dashboard',
      children: [
        { path: 'dashboard', component: () => import('@/views/Dashboard/index.vue') },
        { path: 'article', component: () => import('@/views/Article/index.vue') }
      ]
    },
    { path: '/login', component: () => import('@/views/Login/index.vue') },
    { path: '/update-password', component: () => import('@/views/UpdatePassword/index.vue') }
  ]
})

const whiteList = ['/login']

router.beforeEach((to, from) => {
  const { token } = loginStore
  if (token) {
    if (to.path === '/login')
      return '/'
    return true
  }
  if (whiteList.includes(to.path))
    return true
  return `/login?redirectUrl=${to.path}`
})

export default router
